package com.xiaozhengkeji.colastartboot.services;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author XiaoZhengRS
 * @QQ 1419158026
 * @date 2022/3/1
 */
@Service("MailBoxService")
@Slf4j
public class MailBoxService {


    private static final String MAIL_BOX_FROM = "aegiscloud@163.com";

    private TemplateEngine templateEngine;
    private JavaMailSender mailSender;

    @Autowired
    public MailBoxService(TemplateEngine templateEngine, JavaMailSender mailSender) {
        this.templateEngine = templateEngine;
        this.mailSender = mailSender;
    }

    /**
     * 发送简单文本文件
     */

    public void sendSimpleEmail(String addressee, String subject, String text) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(MAIL_BOX_FROM);
            message.setTo(addressee);
            message.setSubject(subject);
            message.setText(text);
            mailSender.send(message);
        } catch (Exception e) {
            log.info("发送{}出错,标题{}", addressee, subject);
        }
    }


    /**
     * 发送注册邮件
     */
    @Async
    public void sendRegisterUserEmail(String addressee, String verificationCode, String username) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setSubject("欢迎注册AegisCloud");
            helper.setFrom(MAIL_BOX_FROM);
            helper.setTo(addressee);
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("v1", username + " 欢迎注册!请在10分钟内完成注册!");
            context.setVariable("v2", "您注册帐户" + username + "所需的邮箱令牌验证码 为：");
            context.setVariable("verificationCode", verificationCode);
            String process = templateEngine.process("register.html", context);
            helper.setText(process, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
